import { defineStore } from 'pinia'
import { getDocuments } from '@/api/documents'
import { ElMessage } from 'element-plus'

export const useDocumentsStore = defineStore('documents', {
  state: () => ({
    documents: [],
    loading: false,
    total: 0
  }),

  actions: {
    // 获取文档列表
    async fetchDocuments() {
      this.loading = true
      try {
        const response = await getDocuments()
        if (response.data && Array.isArray(response.data.list)) {
          this.documents = response.data.list
          this.total = response.data.total
        } else {
          this.documents = []
          this.total = 0
        }
        return this.documents
      } catch (error) {
        ElMessage.error('获取文档列表失败')
        console.error('获取文档列表失败:', error)
        this.documents = []
        this.total = 0
      } finally {
        this.loading = false
      }
    },

    // 删除文档
    async deleteDocument(id) {
      try {
        await deleteDocument(id)
        this.documents = this.documents.filter(doc => doc.id !== id)
        await this.fetchDocuments()
        ElMessage.success('删除成功')
      } catch (error) {
        ElMessage.error('删除失败')
        console.error('删除文档失败:', error)
      }
    },

    // 更新文档列表
    updateDocumentList(list) {
      if (Array.isArray(list)) {
        this.documents = list
      }
    }
  }
}) 